

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.IO;
using JTC.MiniCommerce.Core;
using JTC.MiniCommerce.Localization;
using JTC.MiniCommerce.Store;
using SubSonic;
using SubSonic.Utilities;

namespace JTC.MiniCommerce.Web {
  public partial class catalog : System.Web.UI.Page {

    #region Member Variables

    private int categoryId = 0;
    private int manufacturerId = 0;
    private decimal priceStart = 0;
    private decimal priceEnd = 0;
    private PagedDataSource pagedDataSource = new PagedDataSource();
    DataSet breadCrumbs;
    private Category category;

    #endregion

    #region Page Events

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e) {
      try {
        categoryId = Utility.GetIntParameter("cid");
        manufacturerId = Utility.GetIntParameter("mid");
        decimal.TryParse(Utility.GetParameter("ps"), out priceStart);
        decimal.TryParse(Utility.GetParameter("pe"), out priceEnd);

        LogStatistics();
        LoadCategoryInfo();
        LoadBreadCrumbs();
        LoadPageTitle();
        LoadProducts();
        LoadNarrowByManufacturer();
        LoadNarrowByPrice();
      }
      catch (Exception ex) {
        Logger.Error(typeof(catalog).Name + ".Page_Load", ex);
        throw;
      }
    }

    #endregion

    #region Methods

    #region Protected

    /// <summary>
    /// Gets the manufacturer URL.
    /// </summary>
    /// <param name="manufacturerId">The manufacturer id.</param>
    /// <returns></returns>
    protected string GetManufacturerUrl(string manufacturerId) {
      return string.Format("~/catalog.aspx?cid={0}&mid={1}", categoryId, manufacturerId);
    }

    /// <summary>
    /// Gets the formatted price range.
    /// </summary>
    /// <param name="lowRange">The low range.</param>
    /// <param name="hiRange">The hi range.</param>
    /// <returns></returns>
    protected string GetFormattedPriceRange(string lowRange, string hiRange) {
      return string.Format("{0} - {1}", StoreUtility.GetFormattedAmount(lowRange, true), StoreUtility.GetFormattedAmount(hiRange, true));
    }

    /// <summary>
    /// Gets the price range URL.
    /// </summary>
    /// <param name="lowRange">The low range.</param>
    /// <param name="hiRange">The hi range.</param>
    /// <returns></returns>
    protected string GetPriceRangeUrl(string lowRange, string hiRange) {
      return string.Format("~/catalog.aspx?cid={0}&ps={1}&pe={2}", categoryId, lowRange, hiRange);
    }

    #endregion

    #region Private

    /// <summary>
    /// Loads the narrow by price.
    /// </summary>
    private void LoadNarrowByPrice() {
      if(Master.SiteSettings.DisplayNarrowByPrice) {
        DataSet ds = new CategoryController().FetchCategoryPriceRanges(categoryId);
        if(ds.Tables[0].Rows.Count > 0) {
          LocalizationUtility.AddPanelText(pnlNarrowByPrice);
          rptrNarrowByPrice.DataSource = ds;
          rptrNarrowByPrice.DataBind();
        }
      }
    }

    /// <summary>
    /// Loads the narrow by manufacturer.
    /// </summary>
    private void LoadNarrowByManufacturer() {
      if(Master.SiteSettings.DisplayNarrowByManufacturer) {
        DataSet ds = new CategoryController().FetchCategoryManufacturers(categoryId);
        if(ds.Tables[0].Rows.Count > 0) {
          LocalizationUtility.AddPanelText(pnlNarrowByManufacturer);
          rptrNarrowByManufacturer.DataSource = ds;
          rptrNarrowByManufacturer.DataBind();
        }
      }
    }

    /// <summary>
    /// Logs the statistics.
    /// </summary>
    private void LogStatistics() {
      if (Master.SiteSettings.CollectBrowsingCategory) {
        BrowsingLog browsingLog = new BrowsingLog();
        browsingLog.BrowsingBehaviorId = (int)BrowsingBehaviour.Browsing_Category;
        browsingLog.RelevantId = categoryId;
        browsingLog.UserName = WebUtility.GetUserName();
        browsingLog.Url = Request.Url.ToString();
        browsingLog.SessionId = WebUtility.SessionId();
        browsingLog.Save("System");
      }
    }

    /// <summary>
    /// Loads the category info.
    /// </summary>
    private void LoadCategoryInfo() {
      category = new Category(categoryId);
      if (!string.IsNullOrEmpty(category.ImageFile)) {
        if (File.Exists(Server.MapPath(category.ImageFile))) {
          hlCategory.ImageUrl = category.ImageFile;
          hlCategory.NavigateUrl = Request.Url.ToString();
        }
      }
    }

    /// <summary>
    /// Loads the page title.
    /// </summary>
    private void LoadPageTitle() {
      string pageTitle = Master.SiteSettings.SiteName;
      foreach (DataRow dr in breadCrumbs.Tables[0].Rows) {
        pageTitle += string.Format(" :: {0}", dr["Name"]);
      }
      if (manufacturerId > 0) {
        Manufacturer manufacturer = new Manufacturer(manufacturerId);
        pageTitle += string.Format(" :: {0}", manufacturer.Name);
      }
      if (priceStart >= 0 && priceEnd > 0) {
        pageTitle += string.Format(" :: {0} - {1}", StoreUtility.GetFormattedAmount(priceStart, true), StoreUtility.GetFormattedAmount(priceEnd, true));
      }
      Page.Title = pageTitle;
    }

    /// <summary>
    /// Loads the bread crumbs.
    /// </summary>
    private void LoadBreadCrumbs() {
      breadCrumbs = new CategoryController().FetchCategoryBreadCrumbs(categoryId);
      xmlDataSource.EnableCaching = false;
      xmlDataSource.Data = breadCrumbs.GetXml();
    }

    /// <summary>
    /// Loads the products.
    /// </summary>
    private void LoadProducts() {
      pagedDataSource.AllowPaging = true;
      pagedDataSource.PageSize = Master.SiteSettings.CatalogItems;
      int currentPageIndex = 0;
      int.TryParse(Utility.GetParameter("p"), out currentPageIndex);
      pagedDataSource.CurrentPageIndex = currentPageIndex;

      if (manufacturerId > 0) {
        pagedDataSource.DataSource = new ProductController().FetchProductsByCategoryIdAndManufacturerId(categoryId, manufacturerId);
      }
      else if (priceStart >= 0 && priceEnd > 0) {
        pagedDataSource.DataSource = new ProductController().FetchProductsByCategoryIdAndPriceRange(categoryId, priceStart, priceEnd);
      }
      else {
        pagedDataSource.DataSource = new ProductController().FetchProductsByCategoryId(categoryId);
      }

      topPager.PagedDataSource = pagedDataSource;
      bottomPager.PagedDataSource = pagedDataSource;
      catalogList.PagedDataSource = pagedDataSource;
    }

    #endregion

    #endregion

  }
}
